package com.hxzy.config.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.json.JSONUtil;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.vo.R;
import com.hxzy.service.impl.TokenService;
import com.hxzy.util.ShopThreadLocalUtil;
import com.hxzy.vo.AdminLoginVO;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 后台令牌的拦截器校验
 */
@Log4j2
@Component
public class AdminTokenValidatorInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService  tokenService;

    /**
     * 在执行Controller之前做的事情
     * @param request
     * @param response
     * @param handler    HandlerMethod 正在执行的哪个类的中的哪个方法(代理对象)
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String jwtToken= request.getHeader("Authorization");

        AdminLoginVO adminLoginVO = this.tokenService.validatorToken(jwtToken);

        //把数据存储到当前线程中
        ShopThreadLocalUtil.adminThreadLocal.set(adminLoginVO);

        //当前拦截器放行，进行到下一个拦截器(如果有)
        return true;
    }

    /**
     * 在执行完成Controller方法之后做的事情
     * @param request
     * @param response
     * @param handler         HandlerMethod 执行完成的某个类中的某个方法
     * @param modelAndView   返回的结果
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //移出本地线程池的数据   (移出内存中的不用数据)
        ShopThreadLocalUtil.adminThreadLocal.remove();
    }

}
